package com.company.test16;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Arc2D;
import java.util.ArrayList;

/**
 * Created by Administrator on 2016.9.5.
 */
public class Test1623 extends JFrame{
    public Test1623(){
        this.add(new pointPanel());
    }

    public static void main(String[] args){
        JFrame frame=new Test1623();

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300,300);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
        frame.setTitle("随机生成点");
    }

    class pointPanel extends JPanel{
        int[] number1;
        int[] number2;
        double minDistance= Double.MAX_VALUE;
        ArrayList<int[]> coordinate=new ArrayList<>();

        public pointPanel(){
            Timer timer=new Timer(1000,new TimerListner());
            timer.start();
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);

            if(coordinate.size()>1){
                for (int[] point:coordinate){
                    g.drawOval(point[0],point[1],8,8);
                }

                g.fillOval(number1[0],number1[1],8,8);
                g.fillOval(number2[0],number2[1],8,8);
            }
        }

        //计算出最近的两个点
        public void calculate(int[] newPoint){

            int[] doll=null;

            double minDistance= Double.MAX_VALUE;
            for (int i=0;i<coordinate.size();i++){
                double distance=Math.pow(newPoint[0]-coordinate.get(i)[0],2)
                        +Math.pow(newPoint[1]-coordinate.get(i)[1],2);
                if(minDistance>distance){
                    minDistance=distance;
                    doll=coordinate.get(i);
                }
            }

            if(minDistance<this.minDistance){
                this.minDistance=minDistance;
                this.number1=doll;
                this.number2=newPoint;
            }

            coordinate.add(newPoint);
        }

        class TimerListner implements ActionListener{
            @Override
            public void actionPerformed(ActionEvent e) {
                int[] newPoint=new int[2];
                newPoint[0]=(int)(Math.random()*300);
                newPoint[1]=(int)(Math.random()*300);
                int z=0;
                //判断是否与已知点重叠
                for(int[] point:coordinate){
                    if(point.equals(newPoint)){
                        z=1;
                    }
                }

                if(coordinate.size()>1&&z==0){
                    calculate(newPoint);
                }else if(z==0){
                    coordinate.add(newPoint);
                }

                repaint();
            }
        }
    }
}
